package com.goodmr.passport.auth;

import org.springframework.stereotype.Service;

import java.sql.Timestamp;

/**
 * 验证码数据逻辑实现（数据库）
 *
 * @author <a href="mailto:bingdong13@msn.com">bigo</a>
 */
@Service("verifyCodeDaoImpl")
class VerifyCodeDaoImpl implements VerifyCodeDao {

    private final VerifyCodeRepository verifyCodeRepository;

    public VerifyCodeDaoImpl(VerifyCodeRepository verifyCodeRepository) {
        this.verifyCodeRepository = verifyCodeRepository;
    }

    /**
     * 生成随机验证码
     *
     * @param receiver 接收者标识
     * @param code     验证码
     * @param timeout  过期时间（s）
     */
    @Override
    public void generate(String receiver, String code, long timeout) {

        Timestamp createdAt = new Timestamp(System.currentTimeMillis());
        Timestamp expiredAt = new Timestamp(System.currentTimeMillis() + timeout * 1000);

        VerifyCodeEntity entity = verifyCodeRepository.findByReceiver(receiver);

        if (null == entity) {
            entity = new VerifyCodeEntity();
            entity.setReceiver(receiver);
        }

        entity.setCode(code);
        entity.setCreatedAt(createdAt);
        entity.setExpiredAt(expiredAt);

        verifyCodeRepository.save(entity);
    }

    /**
     * 校验验证码是否正确
     *
     * @param receiver 接收者标识
     * @param code     验证码
     * @return boolean
     */
    @Override
    public boolean verify(String receiver, String code) {

        boolean result = false;

        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        VerifyCodeEntity entity = verifyCodeRepository.findByReceiver(receiver);

        if (null != entity && entity.getCode().equals(code)) {

            if (timestamp.before(entity.getExpiredAt())) {
                result = true;
            } else {
                verifyCodeRepository.delete(entity);
            }
        }

        return result;
    }

    /**
     * 删除随机验证码
     *
     * @param receiver 接收者标识
     */
    @Override
    public void remove(String receiver) {

        VerifyCodeEntity entity = verifyCodeRepository.findByReceiver(receiver);

        if (null != entity) {
            verifyCodeRepository.delete(entity);
        }
    }
}
